<?php

namespace app\api\controller\v1\posts;

use app\api\controller\v1\wechat\AuthController;
use app\dao\crud\PostsTypesDao;
use app\model\crud\PostsTypes;
use app\model\crud\Votes;
use app\model\crud\VotesHistory;
use app\Request;
use app\services\crud\PostsServices;
use app\services\crud\PostsTypesServices;
use app\services\crud\VotesHistoryServices;
use app\services\crud\VotesServices;

/**
 * 帖子
 */
class PostsController extends AuthController
{
    /**
     * @var PostsServices
     */
    protected $service;

    /**
     * PostsServices constructor.
     * @param PostsServices $services
     */
    public function __construct(PostsServices $services)
    {
        $this->service = $services;
    }

    /**
     * 新增帖子
     * @param Request $request
     * @return mixed
     */
    public function add(Request $request) {
        $data = $request->postMore([
            ['title', ''],
            ['content', ''],
            ['user_id', ''],
            ['price',0],
            ['phone',0],
            ['universit_id', ''],
            ['post_type',3],
            ['vote_end_time',''],
            ['vote_start_time',''],
            ['images', []],
        ]);
        $tpImage = $request->postMore([
            ['tp_images',[]]
        ]);


        $data['status'] = 1;
        $data['user_id'] = $request->uid();
        $data['images'] = json_encode($data['images']);
        $data['add_time'] = time();

        $data['vote_start_time'] = strtotime($data['vote_start_time']) ;
        $data['vote_end_time'] = strtotime($data['vote_end_time']);
        $posts =  $this->service->crudSave($data);
        if(count($tpImage['tp_images']) > 0 && $posts['id'] > 0){
            $votesService = app()->make(VotesServices::class);
            foreach ($tpImage['tp_images'] as $key=>&$row){
                $row['posts_id'] = intval($posts->id);
                $row['num'] =0;
                $votesService->crudSave($row);
            }
        }

        return app('json')->success(100021);
    }

    /**
     * 修改帖子
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request) {
        $data = $request->postMore([
            ['id', 0],
            ['title', ''],
            ['content', ''],
            ['user_id', ''],
            ['price',0],
            ['phone',0],
            ['universit_id', ''],
            ['post_type',3],
            ['images', []],

        ]);

//        validate(\app\adminapi\validate\crud\PostsValidate::class)->check($data);

        $data['images'] = json_encode($data['images']);

        $post = $this->service->get($data['id']);
        if ($post['user_id'] != $request->uid()) {
            return app('json')->fail("您没有权限修改此帖子");
        }
        if ($post['status'] == 4){
            return app("json")->fail("当前帖子已经被锁定，无法修改");
        }
        $this->service->crudUpdate((int)$data['id'], $data);
        return app('json')->success("修改成功");
    }

    /**
     * 帖子列表
     * @param Request $request
     * @return mixed
     */
    public function pageList(Request $request) {
        $where = $request->getMore([
            ['title', ''],
            ['user_id', ''],
            ['content',''],
            ['post_type',''],
            ['universit_id', ''],
        ]);
//        $where['user_id'] = $request->uid();

        return app('json')->success($this->service->getCrudListIndex($where));
    }

    /**
     * 删除帖子
     * @param Request $request
     * @return mixed
     */
    public function delete(Request $request) {
        $where = $request->postMore([
            ['id', 0]
        ]);
        $posts = $this->service->get($where['id']);
        if ($posts['user_id'] != $request->uid()) {
            return app('json')->fail("您没有权限删除此帖子");
        }
        $this->service->delete($where['id']);
        return app("json")->success("删除成功");
    }

    public function forward(Request $request, $id) {
        $this->service->update($id, ['forward' => $this->service->get($id)['forward'] + 1]);
        return app("json")->success("转发成功");
    }

    public function details(Request $request, $id) {
        $data = $this->service->details($id);
        $voteService = app()->make(VotesServices::class);
        $voteList  =  $voteService->getCrudListIndex(['posts_id'=>$data['post']['id']]);
        $data['voteList'] = $voteList;
        $data['endTp'] = false;
        $now = time();
        if(count($voteList) > 0 && $now > $data['post']['vote_end_time'] ){
            $data['endTp'] = true;
        }
        return app("json")->success("查询成功", $data);
    }

    public function type_list()
    {
        $postsTypesModel = app()->make(PostsTypes::class);
        $list = $postsTypesModel->order('sort desc')->select();
        return app('json')->success('查询成功',compact('list'));
    }

    public function getTpHistory(Request $request)
    {
        $uid =  $request->uid();
        $data = $request->postMore(
            ['posts_id','']
        );
        $votesHistoryModel = app()->make(VotesHistory::class);
        $history = $votesHistoryModel->where([
            'user_id'=>$uid,
            'posts_id'=>$data['posts_id']
        ])->find();

        return app('json')->success('查询成功',compact('history')); // TODO: Change the autogenerated stub
    }

    public function tp(Request  $request)
    {
        $uid = $request->uid();
        $data = $request->postMore([
                ['posts_id',0],
                ['vote_id',0],
            ]
        );
        $votesHistoryModel = app()->make(VotesHistory::class);
        $votesModal = app()->make(Votes::class);

        $res = $votesHistoryModel->create(
            [
                'user_id'=>$uid,
                'posts_id'=>$data['posts_id'],
                'vote_id'=>$data['vote_id']
            ]
        );
        if ($res){
           $vote = $votesModal->where('id','=',$data['vote_id'])->find();
           $vote->num = $vote->num + 1 ;
           $vote->save();
        }
        return app('json')->success('成功',compact('res'));
    }
}